package com.example.gobang_system.service.manager;

import com.example.gobang_system.common.pojo.Room;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

@Component
public class RoomManager {
    /**
     * key: roomId
     * value: Room 对象
     */
    private ConcurrentHashMap<String, Room> rooms = new ConcurrentHashMap<>();
    /**
     * key: userId
     * value: roomId
     * 方便根据玩家查询对应房间
     */
    private ConcurrentHashMap<Long, String> userIdToRoomId = new ConcurrentHashMap<>();

    /**
     * 创建游戏房间
     * @param room
     * @param userId1
     * @param userId2
     */
    public void add(Room room, Long userId1, Long userId2) {
        rooms.put(room.getRoomId(), room);
        userIdToRoomId.put(userId1, room.getRoomId());
        userIdToRoomId.put(userId2, room.getRoomId());
    }

    /**
     * 删除游戏房间
     * @param roomId
     * @param userId1
     * @param userId2
     */
    public void remove(String roomId, Long userId1, Long userId2) {
        rooms.remove(roomId);
        userIdToRoomId.remove(userId1);
        userIdToRoomId.remove(userId2);
    }

    /**
     * 通过房间号获取游戏房间
     * @param roomId
     * @return
     */
    public Room getRoomByRoomId(String roomId) {
        return rooms.get(roomId);
    }

    /**
     * 通过玩家 id 获取游戏房间
     * @param userId
     * @return
     */
    public Room getRoomByUserId(Long userId) {
        String roomId = userIdToRoomId.get(userId);
        if (null == roomId) {
            return null;
        }
        return rooms.get(roomId);
    }
}
